#pragma once

#include <iostream>
#include <cstdio>
#include <time.h>
#include <unistd.h>
#include <memory>
#include <string>
#include <filesystem> //c++17文件操作
#include <sstream>
#include <fstream>
#include "Mutex.hpp"
#include "Cond.hpp"

// 日志等级
enum class LogLevel
{
    DEBUG,
    INFO,
    ERROR,
    WARING,
    FATAL
};

std::string LevelTostring(LogLevel level)
{
    switch (level)
    {
    case LogLevel::DEBUG:
        return "DEBUG";
    case LogLevel::INFO:
        return "INFO";
    case LogLevel::ERROR:
        return "ERROR";
    case LogLevel::WARING:
        return "WARING";
    case LogLevel::FATAL:
        return "FATAL";
    default:
        return "UnKnown";
    }
}

// 时间戳格式化
std::string GetCurrentTime()
{
    // 获取时间戳
    time_t currtime = time(nullptr);

    // 格式化时间戳
    struct tm t;
    localtime_r(&currtime, &t);

    // 转化为字符串
    char timebuffer[64];
    snprintf(timebuffer, 64, "%4d-%02d-%02d %02d:%02d:%02d",
             t.tm_year + 1900,
             t.tm_mon + 1,
             t.tm_mday,
             t.tm_hour,
             t.tm_min,
             t.tm_sec);

    return timebuffer;
}

// 刷新策略:基类方法
class LogStrategy
{
public:
    virtual ~LogStrategy() = default;
    virtual void SyncLog(const std::string &Logmessage) = 0;
};

// 显示器策略
class ConsoleLogStrategy : public LogStrategy
{
public:
    ~ConsoleLogStrategy()
    {
    }

    void SyncLog(const std::string &Logmessage) override
    {
        LockGuard lockguard(&_lock);
        std::cout << Logmessage << std::endl;
    }

private:
    Mutex _lock;
};

// 文件刷新

const std::string log_dir = "Log";
const static std::string log_filename = "test_log";

class FileLogStrategy : public LogStrategy
{
public:
    FileLogStrategy(const std::string &dir = log_dir, const std::string filename = log_filename)
        : _dir_path_name(dir), _file_name(filename)
    {
        LockGuard lockguard(&_lock);
        if (std::filesystem::exists(_dir_path_name)) // 判断文件是否存在
        {
            return; // 存在就返回
        }
        try
        {
            std::filesystem::create_directories(_dir_path_name); // 不存在就创建
        }
        catch (std::filesystem::filesystem_error &e) // 文件创建出错
        {
            std::cerr << e.what() << "\r\n"; // 返回错误信息
        }
    }

    void SyncLog(const std::string &Logmessage) override
    {
        {
            LockGuard lockguard(&_lock);
            std::string target = _dir_path_name;
            target += "/";
            target += _file_name;

            std::ofstream out(target.c_str(), std::ios::app); // 输出流以app(追加)模式打开target文件
            if (!out.is_open())
            {
                return;
            }
            out << Logmessage << "\n";
            out.close(); // 关闭文件
        }
    }

    ~FileLogStrategy()
    {
    }

private:
    std::string _dir_path_name; // 路径名
    std::string _file_name;     // 文件名

    Mutex _lock;
};

class Logger
{
public:
    Logger()
    {
    }
    // 刷新策略
    void Enable_Console_LogStrategy()
    {
        _strategy = std::make_unique<ConsoleLogStrategy>();
    }

    void Enable_File_LogStrategy()
    {
        _strategy = std::make_unique<FileLogStrategy>();
    }

    // 构建一条完整日志
    class LogMessage
    {
    public:
        LogMessage(LogLevel level, std::string filename, int line, Logger &logger)
            :_time(GetCurrentTime()),
             _level(level),
             _pid(getpid()),
             _file_name(filename),
             _line(line),
             _logger(logger)
        {
            //stringstream可以将字符串当作流来处理，实现字符串与各种基本数据类型之间的转换
            std::stringstream ss;
            ss << "[" << _time << "] " 
            << "[" << LevelTostring(_level) << "] " 
            << "[" << _pid << "] "
            << "[" << _file_name << "] "
            << "[" << _line << "] "
            << " - ";
            _log_info = ss.str();

        }

        //<<重载
        template <class T>
        LogMessage& operator << (const T& info)
        {
            std::stringstream ssbuffer;
            ssbuffer << info;
            _log_info += ssbuffer.str();
            return *this;//返回当前logmessage对象中，然后可以继续进行该操作
        }

        ~LogMessage()
        {
            if(_logger._strategy)
            {
                _logger._strategy->SyncLog(_log_info);//将日志内容刷新出去
            }
        }

    private:
        //日志格式
        std::string _time;
        LogLevel _level;
        pid_t _pid;
        std::string _file_name;
        int _line;

        std::string _log_info;//整合所有信息合成一条完整日志
        Logger &_logger;//提供刷新策略
    };

    LogMessage operator()(LogLevel level, std::string filename, int line)
    {
        return LogMessage(level, filename, line, *this);//创建一个LogMessage的临时对象
    }

    ~Logger()
    {
    }

private:
    std::unique_ptr<LogStrategy> _strategy; // 刷新策略
};

Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define Console() logger.Enable_Console_LogStrategy()
#define File() logger.Enable_File_LogStrategy()

